package 预科0104ChattingRoom_Q5;

import java.io.*;
import java.net.Socket;

public class Function {
	
	 public static void Stringsend(String msg, String name) {
	        PrintStream printStream = null;
	        try {
	            String msg1 = name + "：" + msg;
	            for (Socket s0: ServerTest.sockets) {
	                if (!s0.isClosed()) {
	                    printStream = new PrintStream(s0.getOutputStream());
	                    printStream.println(msg1);
	                }
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
    public static void FileSend(Socket socket, File file) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(socket.getOutputStream());
            byte[] bytes = new byte[1024];
            int res = 0;
            while ((res = bis.read(bytes)) != -1){

                bos.write(bytes,0,res);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void FileReceiver(int socketNum,String filename){

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;

        try {
            bos = new BufferedOutputStream(new FileOutputStream(ServerTest.severfile
                    + "/" + filename));
            bis = new BufferedInputStream(ServerTest.sockets.get(socketNum).getInputStream());

            byte[] bytes = new byte[1024];
            int res = 0;
            while ((res = bis.read(bytes)) != -1) {
                bos.write(bytes,0,res);
                bos.flush();
                if(res < 1024 ){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void Fileshare(int socketNum,String filename){

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(ServerTest.severfile
                    + "/" + filename));
            bos = new BufferedOutputStream(ServerTest.sockets.get(socketNum).getOutputStream());

            byte[] bytes = new byte[1024];
            int res = 0;
            while ((res = bis.read(bytes)) != -1) {
                bos.write(bytes,0,res);
                bos.flush();
                if(res < 1024 ){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
